package com.example.micro.netty.server.nettygroup;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

public class GroupChatServer {

    private final int port;//监听端口

    public GroupChatServer(int port) {
        this.port = port;
    }

    public void run() throws InterruptedException {

        //创建两个线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workderGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workderGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {

                            //获取到pipeline
                            ChannelPipeline channelPipeline = socketChannel.pipeline();

                            //向pipeline加入解码器
                            channelPipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));

                            //向pipeline加入编码器
                            channelPipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));

                            //加入自己的业务处理handler
                            channelPipeline.addLast(new GroupChatServerHandler());

                        }
                    });
            System.out.println("netty 服务器启动");

            //todo  为什么是sync呢？
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();

            channelFuture.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully();
            workderGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new GroupChatServer(7000).run();
    }

}


